<template>
    <section>
        <a-row :gutter="16" class="mb-16">
            <a-col :span="12">
                <div class="card" style="min-height:100%;padding: 24px;">
                    <div class="card-header" style="margin-bottom:12px;">
                        <span class="card-title" style="margin-right: 0;">可用余额</span>
                        <a-tooltip placement="top" title="当前账户可用于支付的金额，包含正在开机状态的按量付费/竞价实例使用的即将扣除的金额">
                            <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                        </a-tooltip>
                        <a-button type="link" class="card-opt" @click="router.push('/costDetail')">查看</a-button>
                    </div>

                    <div class="card-content">
                        <a-row>
                            <a-col :span="12">
                                <div class="col-money fz-32 mb-24"><span class="fz-14">￥</span>{{ accountInfo.balance }}
                                </div>
                                <div>
                                    <a-button type="primary" class="mr-24" style="width: 96px;height: 32px;"
                                        @click="router.push('/recharge')">充值</a-button>
                                    <a-button style="width: 96px;height: 32px;"
                                        @click="router.push('/withdrawal')">提现</a-button>
                                </div>
                            </a-col>
                            <a-col :span="12"
                                style="text-align: right;display: flex;flex-direction: column;justify-content: center;">
                                <BalanceWaring />
                            </a-col>
                        </a-row>
                    </div>
                </div>
            </a-col>

            <a-col :span="12">
                <div class="card" style="min-height:100%;display: flex;flex-direction: column;padding: 24px;">
                    <div class="card-header" style="margin-bottom:12px;">
                        <span class="card-title">卡券/发票</span>
                    </div>

                    <div class="card-content" style="flex:1;display: flex;">
                        <div class="card-flex">
                            <div class="flex-1">
                                <div class="col-8A93A7 fz-14 mb-16" @click="goVoucher">代金券
                                    <RightOutlined />
                                </div>

                                <div class="col-223354 fz-14">
                                    <span>¥{{ accountInfo?.userTicket?.amount }}</span>
                                    <span>（{{ accountInfo?.userTicket?.count }}）</span>
                                </div>
                            </div>

                            <div class="line"></div>

                            <div class="flex-1" style="text-align: right;">
                                <div class="col-8A93A7 fz-14 mb-16" @click="router.push('/invoice')">可开票金额
                                    <RightOutlined />
                                </div>

                                <div class="col-223354 fz-14">
                                    <span>¥{{ accountInfo?.invoiceInfo?.amount || 0 }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </a-col>
        </a-row>

        <div class="card">
            <div class="card-header" style="margin-bottom:12px;">
                <span class="card-title" style="margin-right: 0;">本月消费</span>
                <a-tooltip placement="top" title="每天凌晨00:00更新，不包含当日数据">
                    <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                </a-tooltip>

                <a-button type="link" class="card-opt" @click="router.push('/costDetail')">查看</a-button>
            </div>

            <div class="card-content">
                <a-table :dataSource="monthBillList.productBillList" class="mb-16" bordered>
                    <a-table-column key="subject" title="产品" data-index="subject">
                        <template #default="{ record }">
                            {{ selectDictLabel(billStatusEnum, record.subject) }}
                        </template>
                    </a-table-column>
                    <a-table-column key="totalOriginAmount" title="原价(元)" data-index="totalOriginAmount" align="right" />
                    <a-table-column key="totalDiscountAmount" title="优惠金额(元)" data-index="totalDiscountAmount"
                        align="right" />
                    <a-table-column key="totalPayAmount" title="应付金额(元)" data-index="totalPayAmount" align="right" />
                    <a-table-column key="totalVoucherAmount" title="代金券抵扣金额(元)" data-index="totalVoucherAmount"
                        align="right" />
                    <a-table-column key="totalBalanceAmount" title="账户余额支付(元)" data-index="totalBalanceAmount"
                        align="right" />

                    <template #summary>
                        <a-table-summary-row>
                            <a-table-summary-cell>合计</a-table-summary-cell>
                            <a-table-summary-cell align="right">
                                <a-typography-text>{{ monthBillList.totalOriginAmount }}</a-typography-text>
                            </a-table-summary-cell>
                            <a-table-summary-cell align="right">
                                <a-typography-text>{{ monthBillList.totalDiscountAmount }}</a-typography-text>
                            </a-table-summary-cell>
                            <a-table-summary-cell align="right">
                                <a-typography-text>{{ monthBillList.totalPayAmount }}</a-typography-text>
                            </a-table-summary-cell>
                            <a-table-summary-cell align="right">
                                <a-typography-text>{{ monthBillList.totalVoucherAmount }}</a-typography-text>
                            </a-table-summary-cell>
                            <a-table-summary-cell align="right">
                                <a-typography-text>{{ monthBillList.totalBalanceAmount }}</a-typography-text>
                            </a-table-summary-cell>
                        </a-table-summary-row>

                    </template>
                </a-table>
            </div>
        </div>

        <div class="card">
            <div class="card-header" style="margin-bottom:12px;">
                <span class="card-title" style="margin-right: 0;">消费趋势</span>
                <a-tooltip placement="top" title="每天凌晨00:00更新，不包含当日数据">
                    <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                </a-tooltip>
                <a-select ref="select" style="width:180px;" class="card-opt" v-model:value="Latitude" allowClear @change="latitudeChange">
                    <a-select-option value="weekly">近7天</a-select-option>
                    <a-select-option value="last_month">近1月</a-select-option>
                    <a-select-option value="monthly">近6月</a-select-option>
                </a-select>
            </div>

            <div class="card-content" style="height:400px;">
                <div id="columnarEchart" ref="charts" style="width:100%;height:100%;"></div>
            </div>
        </div>

    </section>
</template>

<script setup name="CostCenter">
import * as echarts from 'echarts';
import { ref, onMounted } from 'vue'
import { getBillDateApi, getBillTrendApi } from 'api/modules/api.cost'
import dayjs from 'dayjs';
import {
    RightOutlined,
    QuestionCircleOutlined
} from '@ant-design/icons-vue';
import { useRouter } from 'vue-router'
import userInfoStore from '@/stores/userInfo.js'
import BalanceWaring from '@/components/common/BalanceWaring.vue';
import { selectDictLabel } from '@/libs/util.common'

const accountInfo = ref({})
accountInfo.value = userInfoStore().accountInfo
const router = useRouter()

// 获取月度账单
const monthBillList = ref([])
const getMonthBill = () => {
    const billDate = dayjs().format('YYYY-MM')
    getBillDateApi(billDate).then(res => {
        monthBillList.value = res.data.bill
    })
}

getMonthBill()

// 是否开启余额预警
const balanceWaringVisible = ref(false)

/**
 * 页面初始化
 */
onMounted(async () => {
    await getBillTrend()
    init()
});

// 消费趋势
let myChart = null
const charts = ref()
function init() {
    myChart = echarts.init(charts.value);
    let option = {
        color: ['#4DCB73', '#FAAD14'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            },
            valueFormatter: function (value) {
                return value + '元';
            }
        },
        legend: {
            data: ['应付金额', '实付金额'],
            bottom: '10',
            icon: 'rect'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: 50,
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: BillTrendList.value.date
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '应付金额',
                type: 'line',
                areaStyle: {},
                smooth: true,
                emphasis: {
                    focus: 'series'
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(77, 203, 115, 0.40)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(77, 203, 115, 0.00)'
                        }
                    ])
                },
                data: BillTrendList.value.payAmount
            },
            {
                name: '实付金额',
                type: 'line',
                areaStyle: {},
                smooth: true,
                emphasis: {
                    focus: 'series'
                },
                showSymbol: false,
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(250, 173, 20, 0.40)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(250, 173, 20, 0.00)'
                        }
                    ])
                },
                data: BillTrendList.value.balanceAmount
            }
        ]
    };

    option && myChart.setOption(option);
}

// 切换时间维度
const Latitude = ref('weekly')
const BillTrendList = ref([])
async function getBillTrend() {
    const res = await getBillTrendApi(Latitude.value)
    if (res.code != 0) {
        return
    }

    BillTrendList.value = res.data.List || []
    BillTrendList.value.payAmount = BillTrendList.value.map(item => {
        return Number(item.payAmount)
    })

    BillTrendList.value.balanceAmount = BillTrendList.value.map(item => {
        return Number(item.balanceAmount)
    })

    BillTrendList.value.date = BillTrendList.value.map(item => {
        return dayjs( item.date).format('YYYY-MM-DD')
    })
}

async function latitudeChange() {
    await getBillTrend()
    init()
}

const goVoucher = () => {
    router.push('/voucher')
}

// 账单类型
const billStatusEnum = [
    {
        label: '云服务器',
        value: 'instance'
    },
    {
        label: '实例存储',
        value: 'instance_storage'
    },
    {
        label: '网盘存储',
        value: 'net_disk'
    },
    {
        label: '镜像存储',
        value: 'image'
    }
]

</script>

<style scoped lang="scss">
.card {
    background: #fff;
    padding: 15px 20px;
    margin-bottom: 15px;
    border-radius: 6px;

    .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 24px;

        .card-title {
            font-weight: 550;
            color: #223354;
            margin-right: 20px;
        }

        .card-opt {
            margin-left: auto;
        }
    }

    .card-content {

        .card-flex {
            display: flex;
            flex: 1;

            .flex-1 {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: center;
            }
        }

        .line {
            height: auto;
            width: 1px;
            background: rgba(216, 220, 229, 0.43);
        }
    }
}
</style>
